package com.joolun.web.controller.common;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.concurrent.TimeUnit;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson2.JSONObject;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.joolun.common.annotation.Anonymous;
import com.joolun.common.utils.StringUtils;
import com.joolun.system.domain.SysConfig;
import com.joolun.system.domain.SysSmsLog;
import com.joolun.system.service.ISysSmsLogService;
import com.joolun.web.controller.tool.SendSmsUtil;
import jakarta.annotation.Resource;
import javax.imageio.ImageIO;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.google.code.kaptcha.Producer;
import com.joolun.common.config.JooLunConfig;
import com.joolun.common.constant.CacheConstants;
import com.joolun.common.constant.Constants;
import com.joolun.common.core.domain.AjaxResult;
import com.joolun.common.core.redis.RedisCache;
import com.joolun.common.utils.sign.Base64;
import com.joolun.common.utils.uuid.IdUtils;
import com.joolun.system.service.ISysConfigService;

/**
 * 验证码操作处理
 * 
 * @author ruoyi
 */
@RestController
@Slf4j
public class CaptchaController
{
    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private RedisCache redisCache;
    
    @Autowired
    private ISysConfigService configService;

    @Autowired
    private ISysSmsLogService iSysSmsLogService;

    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    public AjaxResult getCode(HttpServletResponse response) throws IOException
    {
        AjaxResult ajax = AjaxResult.success();
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        ajax.put("captchaEnabled", captchaEnabled);
        if (!captchaEnabled)
        {
            return ajax;
        }

        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;

        String capStr = null, code = null;
        BufferedImage image = null;

        // 生成验证码
        String captchaType = JooLunConfig.getCaptchaType();
        if ("math".equals(captchaType))
        {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        }
        else if ("char".equals(captchaType))
        {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }

        redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try
        {
            ImageIO.write(image, "jpg", os);
        }
        catch (IOException e)
        {
            return AjaxResult.error(e.getMessage());
        }

        ajax.put("uuid", uuid);
        ajax.put("img", Base64.encode(os.toByteArray()));
        return ajax;
    }

    /**
     * 未登录获取短信验证码
     */
    @GetMapping("/common/sendSms")
    @Anonymous
    public AjaxResult sendSms(String mobile) throws IOException {
//        // 验证图形验证码
//        String verifyImageCode = CacheConstants.CAPTCHA_CODE_KEY + num;
//        String cacheCode = redisCache.getCacheObject(verifyImageCode);
//        if(StringUtils.isEmpty(cacheCode)  || !cacheCode.equals(code)){
//            return AjaxResult.error(0,"图形验证码不正确");
//        }
        // 短信验证码key
        // 获取redis验证码
        String captcha = redisCache.getCacheObject(mobile);
        // 一分钟之内不能重复发送短信
        if (ObjectUtil.isNotEmpty(captcha)) {
            return AjaxResult.error(-1,"请勿频繁发送,1分钟限1次");
        }
        // 生成验证码
        String smsCode = RandomUtil.randomNumbers(4);
        //获取短信资源配置信息
        SysConfig sysConfig = configService.selectConfigObject("sms.config.key");
        if(sysConfig == null){
            AjaxResult.error(-1,"请检查配置短信平台信息");
        }
        String accessKeyId = sysConfig.getConfigValue();
        String accessKeySecret = sysConfig.getRemark();
        SendSmsResponse sendSmsResponse = new SendSmsResponse();
        try {
            // TODO:开发测试暂时不发短信
            sendSmsResponse = SendSmsUtil.send(mobile,smsCode,accessKeyId,accessKeySecret);
            // {"body":{"bizId":"658723335198074364^0","code":"OK","message":"OK","requestId":"DCEE31AA-ED79-54FF-B78F-13ACE96C3A24"},"headers":{"access-control-allow-origin":"*","date":"Thu, 26 Dec 2024 07:27:54 GMT","content-length":"110","keep-alive":"timeout=25","x-acs-request-id":"DCEE31AA-ED79-54FF-B78F-13ACE96C3A24","connection":"keep-alive","content-type":"application/json;charset=utf-8","etag":"1kr24UemO6P0arAKSaMaoyQ0","access-control-expose-headers":"*","x-acs-trace-id":"009dd8812e35e6cf6dac3ea0c9bc2774"},"statusCode":200}
            log.info("------短信验证码：{}",smsCode);
        } catch (Exception e) {
            return AjaxResult.error("短信发送失败");
        }
        // 测试数据
//        sendSmsResponse.setStatusCode(200);
//        sendSmsResponse.setBody(new SendSmsResponseBody().setBizId("111"));
        // 短信发送成功
        if (sendSmsResponse.getStatusCode() == 200) {
            // 缓存短信验证码
            redisCache.setCacheObject(mobile, smsCode, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
            SysSmsLog smsLogVo = new SysSmsLog();
            smsLogVo.setLogDate(new Timestamp(System.currentTimeMillis()));
            smsLogVo.setMobile(mobile);
            smsLogVo.setSendStatus(200L);
            smsLogVo.setTemplateId("SMS_472465458");
            smsLogVo.setSmsCode(smsCode);
            smsLogVo.setSmsText(sendSmsResponse.getBody().getBizId());
            iSysSmsLogService.save(smsLogVo);
        }
        log.info("---发送短信返回：{}", JSONObject.toJSONString(sendSmsResponse));
        return AjaxResult.success("发送成功",smsCode);
    }

}
